package com.xiaomengkuan.plugin.service.impl;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.UploadResult;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.Upload;
import com.tencent.cloud.CosStsClient;
import com.xiaomengkuan.common.util.R;
import com.xiaomengkuan.plugin.service.CosService;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.TreeMap;
import java.util.UUID;

/**
 * @author Faraj Mujey
 * -- Creation Time: 2021-01-27 3:48 下午, File Encoding: utf8 --
 */
@Service
@Slf4j
public class CosServiceImpl implements CosService {

    @Value("${qcloud.cos.secretId}")
    private String secretId;
    @Value("${qcloud.cos.secretKey}")
    private String secretKey;
    @Value("${qcloud.cos.region}")
    private String region;
    @Value("${qcloud.cos.bucket}")
    private String bucket;

    @Override
    public String signature() throws Exception {
        TreeMap<String, Object> config = new TreeMap<>();
        config.put("SecretId", secretId);
        config.put("SecretKey", secretKey);
        config.put("durationSeconds", 1800);
        config.put("bucket", bucket);
        config.put("allowPrefix", "*");
        config.put("region", region);
        String[] allowActions = new String[]{
                "name/cos:PutObject",
                "name/cos:PostObject",
                "name/cos:InitiateMultipartUpload",
                "name/cos:ListMultipartUploads",
                "name/cos:ListParts",
                "name/cos:UploadPart",
                "name/cos:CompleteMultipartUpload"
        };
        config.put("allowActions", allowActions);
        JSONObject credential = CosStsClient.getCredential(config);
        return credential.toString();
    }

    public COSClient getCosClient() {
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        Region region = new Region("ap-guangzhou");
        ClientConfig clientConfig = new ClientConfig(region);
        return new COSClient(cred, clientConfig);
    }

    @Override
    public R upload(MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String key =
                    UUID.randomUUID().toString().replace("-", "") + originalFilename.substring(originalFilename.lastIndexOf("."));
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(file.getSize());
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key
                    , inputStream, objectMetadata);
            TransferManager transferManager =
                    new TransferManager(getCosClient());
            Upload upload = transferManager.upload(putObjectRequest);
            UploadResult uploadResult = upload.waitForUploadResult();
            return R.ok().detail("上传成功").put("url", "https://sayclothes" +
                    "-1303192352.cos.ap-guangzhou.myqcloud.com/" + uploadResult.getKey());
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.err();
        }
    }
}
